﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;

namespace DoeObjects
{
	public static class MailManager
	{
		private static List<MailMessage> _mailQueue = new List<MailMessage>();

		public static bool sendMail(MailMessage mail)
		{
			if (Settings.UseMailQueueing &&
				checkIfInTimeSpan(DateTime.Now.TimeOfDay, Settings.QueueMailsFrom, Settings.QueueMailsTo))
			{
				_mailQueue.Add(mail);
			}
			else
			{
				try
				{
					Settings.SimpleMailClient.Send(mail);
				}
				catch (Exception e)
				{ return false; }
			}
			return true;
		}

		public static bool sendMail(string emailAdress, string subject, string htmlMessage, MailPriority priority = MailPriority.Normal)
		{
			if (string.IsNullOrEmpty(emailAdress))
				return false;

			MailMessage mail = new MailMessage();

			mail.From = Settings.SenderAddress;
			mail.To.Add(new MailAddress(emailAdress));
			mail.Subject = subject;
			mail.Priority = priority;
			mail.IsBodyHtml = true;
			mail.Body = htmlMessage;

			return MailManager.sendMail(mail);
		}

		public static void sendQueuedMails()
		{
			foreach (MailMessage mail in _mailQueue)
			{
				try
				{
					Settings.SimpleMailClient.Send(mail);
				}
				catch (Exception e) { }
			}
		}

		private static bool checkIfInTimeSpan(TimeSpan timeToCheck, TimeSpan from, TimeSpan to)
		{
			if (TimeSpan.Compare(from, to) == 0)
				if (timeToCheck == from) return true;
				else return false;
			else if (TimeSpan.Compare(from, to) == 1)
				if ((timeToCheck >= from) || (timeToCheck < to)) return true;
				else return false;
			else
				if ((timeToCheck >= from) && (timeToCheck < to)) return true;
				else return false;
		}
	}
}
